<template>
  <div class="dialog-container">
    <el-dialog
      :title="dialogType==='add'?'添加任务':auditOrHandle === 'e009_01'?'任务处理':auditOrHandle === 'e009_02'?'任务审核':dialogType === 'detail'?'任务详情':'修改任务'"
      :visible="dialogVisible"
      @open="initData"
      @close="closeDialog"
    >
      <el-form
        ref="form"
        :model="dataForm"
        class="dialog-form"
        :rules="rules"
        label-width="110px"
        size="mini"
        :disabled="dialogType === 'detail'"
      >
        <el-row>
          <el-tabs>
            <el-tab-pane label="任务内容">
              <el-col :span="12">
                <el-form-item label="任务名称" prop="taskName">
                  <el-input v-model="dataForm.taskName" placeholder="请输入任务名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目部" prop="projectDepartmentId">
                  <el-select v-model="dataForm.projectDepartmentId" class="w-100" placeholder="请选择" filterable :filter-method="projectDepartmentFilter" @blur="resetOptions" @change="selectBox2">
                    <el-option v-for="item in projectDepartmentOptions" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发布人" prop="publisherId">
                  <el-select v-model="dataForm.publisherId" class="w-100" placeholder="请选择" filterable :filter-method="publisherFilter" @blur="resetOptions">
                    <el-option v-for="item in options" :key="item.id" :label="item.realName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="责任人" prop="responsibleId">
                  <el-select v-model="dataForm.responsibleId" class="w-100" placeholder="请选择" filterable :filter-method="responsiblesFilter" @blur="resetOptions">
                    <el-option v-for="item in options2" :key="item.id" :label="item.realName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="协助人" prop="helperId">
                  <el-select v-model="dataForm.helperId" class="w-100" multiple placeholder="请选择" filterable :filter-method="helpersFilter" @blur="resetOptions">
                    <el-option v-for="item in options3" :key="item.id" :label="item.realName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务类型" prop="taskType">
                  <el-select
                    v-model="dataForm.taskType"
                    class="w-100"
                    placeholder="请选择任务类型"
                  >
                    <el-option
                      v-for="(item,index) in taskTypes"
                      :key="index+'task_type'"
                      :value="item.code"
                      :label="item.codeName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="任务内容" prop="taskContent">
                  <el-input v-model="dataForm.taskContent" type="textarea" :rows="3" placeholder="请输入任务内容" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="dataForm.remark" type="textarea" placeholder="请输入备注" />
                </el-form-item>
              </el-col>
            </el-tab-pane>
          </el-tabs>
          <el-tabs v-if="dialogType !== 'add' && auditOrHandle !== 'e009_01'">
            <el-tab-pane label="完成情况">
              <span>
                <el-col :span="12">
                  <el-form-item label="完成时间" prop="gmtModified">
                    <el-date-picker v-model="taskCompletionSituation.gmtModified" class="w-100" type="date" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="运维表单号" prop="remark">
                    <el-input v-model="dataForm.formNo" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="任务完成描述" prop="operationContent">
                    <el-input v-model="taskCompletionSituation.operationContent" type="textarea" placeholder="" />
                  </el-form-item>
                </el-col>
              </span>
            </el-tab-pane>
          </el-tabs>
          <el-tabs v-if="dialogType !== 'add' && auditOrHandle !== 'e009_01' && auditOrHandle !== 'e009_02'">
            <el-tab-pane label="审核记录">
              <span>
                <el-col :span="12">
                  <el-form-item label="时间" prop="remark">
                    <el-date-picker v-model="auditResults.gmtModified" class="w-100" type="date" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结果" prop="taskStatus">
                    <el-select
                      v-model="dataForm.taskStatus"
                      class="w-100"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="(item,index) in taskStatus"
                        :key="index+'task_status'"
                        :value="item.code"
                        :label="item.codeName"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="意见" prop="operationContent">
                    <el-input v-model="auditResults.operationContent" type="textarea" placeholder="" />
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="auditResults.remark" type="textarea" placeholder="" />
                  </el-form-item>
                </el-col>
              </span>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-form>
      <el-form
        ref="form2"
        :model="dataForm"
        :rules="rules"
        class="dialog-form"
        label-width="110"
        size="mini"
      >
        <el-row>
          <el-form-item v-if="auditOrHandle === 'e009_02'&&auditShow" label="审核意见">
            <el-radio-group v-model="reviewStatus">
              <el-radio
                v-for="(item,index) in reviewStatusList"
                :key="index + 'task_status'"
                :label="item.code"
              >{{ item.codeName }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="auditOrHandle === 'e009_02'&&auditShow" label="意见说明" prop="statusDescription">
            <el-input v-model="dataForm.statusDescription" type="textarea" placeholder="" rows="5" />
          </el-form-item>
          <el-form-item v-if="auditOrHandle === 'e009_01'" label="任务完成描述" prop="statusDescription">
            <el-input v-model="dataForm.statusDescription" type="textarea" placeholder="" rows="5" />
          </el-form-item>
          <el-form-item v-if="dataForm.taskType === 'e008_02' && auditOrHandle === 'e009_01' " label="关联运维表单" prop="taskType">
            <el-select
              v-model="dataForm.maintenanceId"
              class="w-100"
              placeholder="请选择运维表单"
              multiple
            >
              <el-option
                v-for="(item,index) in maintenances"
                :key="index+'task_type'"
                :value="item.id"
                :label="item.formNo"
              />
            </el-select>
          </el-form-item>
        </el-row>
      </el-form>
      <span v-if="dialogType === 'detail'" slot="footer" class="dialog-footer">
        <el-button v-if="auditOrHandle === 'e009_01' && hasBtn('task:report')" :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleUpdate('e009_02')">上报</el-button>
        <el-button v-if="auditOrHandle === 'e009_02' && hasBtn('task:review')" :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleReview(reviewStatus)">提交</el-button>
        <el-button v-if="(auditOrHandle === 'e009_01' && hasBtn('task:report')) || (auditOrHandle === 'e009_02' && hasBtn('task:review'))" size="mini" class="cancel-btn" @click="closeDialog">取消</el-button>
      </span>·
      <span v-if="dialogType === 'add' && hasBtn('task:add')" slot="footer" class="dialog-footer">
        <el-button :loading="saveLoading" class="sure-btn" size="mini" type="primary" @click="handleSave">保存</el-button>
        <el-button size="mini" class="cancel-btn" @click="closeDialog">取消</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { add, review, report } from '@/api/info/task'
import { getProjectPersonnel } from '@/utils/common'
import { getListByUserId } from '@/api/info/projectDepartment'
import { hasBtnPermission as hasBtn, getRoleType } from '@/utils/buttons'
import { getList as getMaintenanceDict } from '@/api/maintenanceManage/index'
import { getList } from '@/api/info/taskProcess'
import { getDictLabel } from '@/utils'
import { getDict } from '@/utils/dict'

export default {
  name: 'AddTaskDialog',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    dialogType: {
      type: String,
      default: 'detail'
    },
    obj: {
      type: Object,
      default: () => {
      }
    }
  },
  data() {
    return {
      saveLoading: false,
      dataForm: {
        id: null,
        ids: [],
        num: null,
        taskName: null,
        taskContent: null,
        taskType: null,
        taskStatus: null,
        projectDepartmentId: '',
        startTime: null,
        remark: null,
        publisherId: '',
        responsibleId: '',
        helperId: [],
        maintenanceId: [],
        statusDescription: null,
        formNo: null
      },
      reviewStatus: 'e009_03',
      reviewStatusList: [],
      taskTypes: [],
      projectDepartments: [],
      publishers: [],
      responsibles: [],
      helpers: [],
      maintenances: [],
      taskStatus: [],
      taskCompletionSituation: {},
      auditResults: {},
      auditOrHandle: null,
      auditShow: false,
      query: {
        page: 1, limit: 10, total: 0,
        taskName: null, taskType: null
      },
      rules: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        taskContent: [{ required: true, message: '请输入任务类容', trigger: 'blur' }],
        taskType: [{ required: true, message: '请选择任务类型', trigger: 'change' }],
        projectDepartmentId: [{ required: true, message: '请选择任项目部', trigger: 'change' }],
        publisherId: [{ required: true, message: '请选择发布人', trigger: 'change' }],
        responsibleId: [{ required: true, message: '请选择任责任人', trigger: 'change' }]
        // helperId: [{ required: true, message: '请选择任协助人', trigger: 'change' }]
      },

      optionsCopy: [],
      optionsCopy2: [],
      options: [],
      options2: [],
      options3: [],

      projectDepartmentOptionsCopy: [],
      projectDepartmentOptions: [],
      value: ''
    }
  },
  created() {
    this.taskTypes = getDict('e008')
    this.taskTypes.shift()
    this.taskStatus = getDict('e009')
  },
  methods: {
    getDictLabel, hasBtn, getProjectPersonnel,
    initData() {
      if (this.dialogType !== 'add') {
        this.conversion()
        this.getTaskProcess()
      }
      this.selectBox()
      // 运维表单选择
      if (this.auditOrHandle === 'e009_01' && this.dialogType === 'detail') {
        this.getMaintenanceList()
      }
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    handleSave() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          add(this.dataForm).then(() => {
            this.$message.success('成功')
            this.$emit('closeDialog')
            this.$emit('flushPage')
            this.clearData()
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    // 上报
    handleUpdate(reviewStatus) {
      this.$refs['form'].validate((valid) => {
        this.dataForm.taskStatus = reviewStatus
        if (valid) {
          this.saveLoading = true
          report(this.dataForm).then(() => {
            this.$message.success('成功')
            this.$emit('closeDialog')
            this.$emit('flushPage')
            this.clearData()
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    // 审核
    handleReview(reviewStatus) {
      this.$refs['form'].validate((valid) => {
        this.dataForm.taskStatus = reviewStatus
        if (valid) {
          this.saveLoading = true
          review(this.dataForm).then(() => {
            this.$message.success('成功')
            this.$emit('closeDialog')
            this.$emit('flushPage')
            this.saveLoading = false
          }).catch(() => {
            this.saveLoading = false
          })
        }
      })
    },
    // 获取下拉框数据
    selectBox() {
      getListByUserId().then((res) => {
        this.projectDepartmentOptionsCopy = res.data.projectDepartments
        this.projectDepartmentOptions = res.data.projectDepartments
        const roleType = getRoleType()
        // 如果不是高管 默认选择自己项目部
        const pid = res.data.projectDepartments[0].id
        if (this.dialogType === 'add' && roleType !== 'e036_02' && roleType !== 'e036_01') {
          this.dataForm.projectDepartmentId = pid
          if (pid) {
            this.selectBox2(pid)
          }
        } else {
          this.selectBox2()
        }
      }).catch(() => {
      })
    },
    selectBox2(pid) {
      // 如果项目部已选择 查询项目部人员
      if (pid) {
        getProjectPersonnel({ 'pid': pid }).then(res => {
          this.optionsCopy = res.data.row
          // 发布人为主管
          this.optionsCopy2 = []
          this.optionsCopy.forEach(value => {
            if (value.roleType === 'e036_03') {
              this.optionsCopy2.push(value)
            }
          })
          this.options = this.optionsCopy2
          this.options2 = res.data.row
          this.options3 = res.data.row
        })
      } else if (this.dialogType !== 'add') {
        getProjectPersonnel().then(res => {
          this.optionsCopy = res.data.row
          // 发布人为主管
          this.optionsCopy2 = res.data.row
          this.options = res.data.row
          this.options2 = res.data.row
          this.options3 = res.data.row
        })
      }
      // 项目部发生改变，候选人员清空
      if (this.dialogType === 'add') {
        if (this.dataForm.publisherId !== '') {
          this.dataForm.publisherId = null
        }
        if (this.dataForm.responsibleId !== '') {
          this.dataForm.responsibleId = null
        }
        if (this.dataForm.helperId !== '') {
          this.dataForm.helperId = []
        }
      }
    },
    // 获取运维单
    getMaintenanceList() {
      getMaintenanceDict().then(value => {
        this.maintenances = value.data.list
      })
      // TODO
    },
    getTaskProcess() {
      getList({ 'taskId': this.dataForm.id }).then(res => {
        res.data.list.forEach(item => {
          if (item.taskProcessOperationType === 'e010_02') {
            this.taskCompletionSituation = item
          } else if (item.taskProcessOperationType === 'e010_03') {
            this.auditResults = item
          }
        })
      })
    },
    // 发布人搜索框
    publisherFilter(val) {
      if (val) {
        // val存在
        this.options = this.optionsCopy2.filter((item) => {
          if (!!~item.realName.indexOf(val) || !!~item.namePym.toLowerCase().indexOf(val.toLowerCase())) {
            return true
          }
        })
      } else {
        // val为空时，还原数组
        this.options = this.optionsCopy2
      }
    },
    // 责任人搜索框
    responsiblesFilter(val) {
      if (val) {
        // val存在
        this.options2 = this.optionsCopy.filter((item) => {
          if (!!~item.realName.indexOf(val) || !!~item.namePym.toLowerCase().indexOf(val.toLowerCase())) {
            return true
          }
        })
      } else {
        // val为空时，还原数组
        this.options2 = this.optionsCopy
      }
    },
    // 协助人搜索框
    helpersFilter(val) {
      if (val) {
        // val存在
        this.options3 = this.optionsCopy.filter((item) => {
          if (!!~item.realName.indexOf(val) || !!~item.namePym.toLowerCase().indexOf(val.toLowerCase())) {
            return true
          }
        })
      } else {
        // val为空时，还原数组
        this.options3 = this.optionsCopy
      }
    },
    // 项目部搜索框
    projectDepartmentFilter(val) {
      if (val) {
        // val存在
        this.projectDepartmentOptions = this.projectDepartmentOptionsCopy.filter((item) => {
          if (!!~item.name.indexOf(val) || !!~item.namePym.toLowerCase().indexOf(val.toLowerCase())) {
            return true
          }
        })
      } else {
        // val为空时，还原数组
        this.projectDepartmentOptions = this.projectDepartmentOptionsCopy
      }
    },
    // 失去焦点还原数组
    resetOptions() {
      this.options = this.optionsCopy2
      this.options2 = this.optionsCopy
      this.options3 = this.optionsCopy
      this.projectDepartmentOptions = this.projectDepartmentOptionsCopy
    },
    closeDialog() {
      this.$emit('closeDialog')
      this.clearData()
      this.$refs['form'].clearValidate()
    },
    conversion() {
      // 回显数据
      this.dataForm = JSON.parse(JSON.stringify(this.obj))
      this.dataForm.statusDescription = null
      this.dataForm.helperId = []
      if (this.obj.helperId !== null) {
        this.obj.helperId.split(',').forEach(item => {
          this.dataForm.helperId.push(parseInt(item))
        })
      }
      // 审核还是处理
      this.auditOrHandle = this.dataForm.taskStatus
      // 审核框是否显示
      this.auditShow = (this.dialogType !== 'add' && this.dataForm.taskStatus === 'e009_01' || this.dataForm.taskStatus === 'e009_02') && this.hasBtn('task:review')
      // 默认选择
      if (this.dataForm.taskStatus !== 'e009_01' && this.dataForm.taskStatus !== 'e009_02') {
        this.reviewStatus = this.dataForm.taskStatus
      }
      // 审核意见选择
      this.reviewStatusList = []
      this.taskStatus.forEach(item => {
        if (item.code === 'e009_03' || item.code === 'e009_04') {
          this.reviewStatusList.push(item)
        }
      })
    },
    clearData() {
      this.dataForm = {
        num: null,
        taskName: null,
        taskContent: null,
        taskType: null,
        taskStatus: null,
        projectDepartmentId: null,
        startTime: null,
        remark: null,
        publisherId: null,
        responsibleId: null,
        helperId: []
      }
      this.auditShow = false
      this.reviewStatus = 'e009_03'
      this.auditOrHandle = null
      this.taskCompletionSituation = {}
      this.auditResults = {}
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
